// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  
  try {
    // 查询用户是否已存在
    const userRes = await db.collection('User')
      .where({ openid })
      .field({
        avatar: 1,
        nickname: 1,
        gender: 1,
        country: 1,
        province: 1,
        city: 1,
        callAICount: 1
      })
      .get();
    
    if (userRes.data.length === 0) {
      // 用户不存在，创建新用户
      const newUser = {
        openid,
        createdAt: db.serverDate(),
        updatedAt: db.serverDate(),
        nickname: '',
        avatar: '',
        wordLearningInfoData: {},
        callAICount: 0
      };
      
      await db.collection('User').add({
        data: newUser
      });
      
      return {
        success: true,
        openid,
        isNewUser: true,
        userInfo: newUser
      };
    } else {
      // 用户已存在
      return {
        success: true,
        openid,
        isNewUser: false,
        userInfo: userRes.data[0]
      };
    }
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
};